<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2006/11/13 15:22:14 $)
// $RCSfile: functions_captcha.php,v $ : $Revision: 1.6 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

global $_captchacolors;
$_captchacolors[] = array(38, 125, 220);
$_captchacolors[] = array(255, 156, 0);
$_captchacolors[] = array(49, 49, 49);

/**
* Whether or not Captcha is supported
*/
function canCaptcha()
{
	global $_SWIFT;

	if (defined("ISMODERNBILL") || defined("ISMODERNBILLV5") || !empty($_SWIFT["user"]["userid"]))
	{
		return false;
	}

	if (function_exists("imagecreate") && function_exists("imagettftext"))
	{
		return true;
	}

	return false;
}

/**
* Generate a captcha image and set the captcha random word in sessions table
*/
function generateCaptcha()
{
	global $dbCore, $_SWIFT, $_captchacolors;

	$font = "./themes/admin_".$_SWIFT["admintheme"]."/captcha.ttf";

    $img = imagecreate(180, 40);
	if (!$img)
	{
//		echo "Cant Create Image";
		return false;
	}

	if (empty($_SWIFT["session"]["captcha"]))
	{
		echo "No Captcha Word Found";
		return false;
	}

	$randomword = $_SWIFT["session"]["captcha"];

	$background = imageColorAllocate($img, 255, 255, 255);
	$captchacolors = count($_captchacolors);
	
	$xind = 0;
	for ($ii=0; $ii<strlen($randomword); $ii++)
	{
		mt_srand ((double) microtime() * 1000000);
		$r = mt_rand(0, count($_captchacolors));
		mt_srand ((double) microtime() * 1000000);
		$a = mt_rand(1, 8);
		mt_srand ((double) microtime() * 1000000);
		$x = mt_rand(1, 12);
		$xind = $xind+15+$x;
		$color = imageColorAllocate($img, $_captchacolors[$r][0], $_captchacolors[$r][1], $_captchacolors[$r][2]);
	    ImageTTFText($img, 15, $a, $xind, 30, $color, $font, substr($randomword, $ii, 1));
	}

	headerNoCache();


    header("Content-type: image/jpeg");
    ImageJPEG($img);

	return true;
}

/**
* Generate the word and store it in db
*/
function generateCaptchaWord()
{
	global $dbCore, $_SWIFT;

	if (empty($_SWIFT["session"]["sessionid"]))
	{
		return false;
	}

	$captchalength = 5;
	$randomword = substr(buildHash(), 0, $captchalength);

	$dbCore->query("UPDATE `". TABLE_PREFIX ."sessions` SET `captcha` = '". $dbCore->escape($randomword) ."' WHERE `sessionid` = '". $dbCore->escape($_SWIFT["session"]["sessionid"]) ."';");

	return true;
}
?>